package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tbvtc.agriculturalcreditchainserver2025.dto.User.UpdateUserDto;
import com.tbvtc.agriculturalcreditchainserver2025.dto.admin.GetAllOrdersDto;
import com.tbvtc.agriculturalcreditchainserver2025.dto.admin.GetAllUserDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Crop;
import com.tbvtc.agriculturalcreditchainserver2025.entity.FarmlandInfo;
import com.tbvtc.agriculturalcreditchainserver2025.entity.FarmlandInfoDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.User;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUser;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUserHolder;

import com.tbvtc.agriculturalcreditchainserver2025.mapper.FarmerMapper;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.block.BlockchainTransaction;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.landInit;
import com.tbvtc.agriculturalcreditchainserver2025.service.*;
import com.tbvtc.agriculturalcreditchainserver2025.utils.*;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.vo.AuthUser;
import com.tbvtc.agriculturalcreditchainserver2025.vo.PageVo;

import com.tbvtc.agriculturalcreditchainserver2025.vo.UserVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.admin.UserInfoVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.user.UpdateUserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@Slf4j
@Tag(name = "管理端")
@RequestMapping("/admin/admin")
@CrossOrigin
public class AdminController {

    @Resource
    private IFarmlandInfoService facilityInfoService;
    @Resource
    private ICropService cropService;
    @Resource
    private IUserService userService;
    @Resource
    private AdminService adminService;
    @Resource
    private FarmerSerive farmerSerive;
    @Resource
    private BlockchainUtils blockchainUtils;
    @Resource
    private BlockBaseUtils blockBaseUtils;
    @Resource
    private FarmerMapper farmerMapper;
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate restTemplate;

    @Operation(summary = "查询所有的初始化土地信息")
    @GetMapping("/getAllLand")
    public Result getAllLand(@RequestParam(defaultValue = "1") Long page, @RequestParam(defaultValue = "10") Long size) {
        Page<FarmlandInfo> infoPage = new Page<>(page, size);
        Page<FarmlandInfo> farmlandInfoPage = facilityInfoService.page(infoPage, null);
        long total = farmlandInfoPage.getTotal();
        List<FarmlandInfo> records = farmlandInfoPage.getRecords();
        PageVo<FarmlandInfo> list = new PageVo<>(total, records);
        return RUtils.success(list);
    }

    @Operation(summary = "查询所有的农作物信息")
    @GetMapping("/getAllCrop")
    public Result getAllCrop(@RequestParam(defaultValue = "1") Long page, @RequestParam(defaultValue = "10") Long size) {
        Page<Crop> infoPage = new Page<>(page, size);
        Page<Crop> cropPage = cropService.page(infoPage, null);
        long total = cropPage.getTotal();
        List<Crop> records = cropPage.getRecords();
        PageVo<Crop> list = new PageVo<>(total, records);
        return RUtils.success(list);
    }

    @Operation(summary = "查看所有用户")
    @PostMapping("/getAllFarmer")
    public Result getAllFarmer(@RequestBody GetAllUserDto getAllUserDto) {
        Page<User> infoPage = new Page<>(getAllUserDto.getPage(), getAllUserDto.getSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .like(StringUtils.hasText(getAllUserDto.getUsername()), User::getUsername, getAllUserDto.getUsername())
                .eq(getAllUserDto.getRoleId()!=null, User::getRoleId, getAllUserDto.getRoleId());

        Page<User> userPage = userService.page(infoPage, wrapper);
        List<UserInfoVo> users = BeanUtil.copyToList(userPage.getRecords(), UserInfoVo.class);
        PageVo<UserInfoVo> pageVo = new PageVo<>(userPage.getTotal(), users);
        return RUtils.success(pageVo);
    }

    @Operation(summary = "禁用启用用户")
    @PutMapping("/disable")
    public Result disableUser(@RequestParam Long id,Integer isDisable) {
        User user = userService.getById(id);
        User isDisable1 = user.setIsDisable(isDisable);
        userService.updateById(isDisable1);
        return RUtils.success();
    }

    @Operation(summary = "认证用户")
    @PutMapping("/isAudit")
    @Parameter(name = "ids", description = "用户id多个id用逗号隔开")
    public Result isAudit(@RequestParam List<Long> ids) {
        ids.forEach(id -> {
            User user = userService.getById(id);
            userService.updateById(user.setIsAudit(0));
        });
        return RUtils.success();
    }

    @Operation(summary = "管理员详情")
    @GetMapping("/getAdmin")
    public Result getAdminInfo() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        Long userId = loginUser.getUserId();
        User user = userService.getById(userId);
        AuthUser authUser = BeanUtil.copyProperties(user, AuthUser.class);
        return RUtils.success(authUser);
    }

    @Operation(summary = "根据id查找土地信息（回显）")
    @GetMapping("/getLandById")
    public Result getLandById(@RequestParam Long id) {
        FarmlandInfo farmlandInfo = facilityInfoService.getById(id);

        return RUtils.success(farmlandInfo);
    }

    @Operation(summary = "根据id修改土地信息")
    @PutMapping("/updateLand")
    public Result updateLandById(@RequestBody FarmlandInfoDto farmlandInfoDto) {
        FarmlandInfo farmlandInfo = BeanUtil.copyProperties(farmlandInfoDto, FarmlandInfo.class);
        facilityInfoService.updateById(farmlandInfo);
        return RUtils.success(farmlandInfo);
    }

    @Operation(summary = "根据id删除土地")
    @DeleteMapping("deleteLandById")
    public Result deleteLandById(@RequestParam Long id) {
        facilityInfoService.removeById(id);
        return RUtils.success();
    }

    @Operation(summary = "增加土地信息")
    @PostMapping("/addLand")
    public Result addLand(@RequestBody landInit landInit) {
             landInit.setCreateTime(LocalDateTime.now());
            farmerMapper.addLand(landInit);
            return RUtils.success();
    }

    @Operation(summary = "获取订单")
    @PostMapping("/getOrders")
    public Result getOrders(@RequestBody GetAllOrdersDto ordersDto) {
        return RUtils.success(adminService.getOrders(ordersDto));
    }

    @Operation(summary = "获取交易信息")


    @GetMapping("/addTr")
    public Result addTr(Long page,Long size) throws Exception {
        blockchainUtils.getBlockTr(blockBaseUtils.getPemFilePath(UserType.ADMIN));
        Gson gson = new GsonBuilder().create();
        Long start = (page - 1) * size;
        List<BlockchainTransaction> collect = restTemplate.opsForZSet()
                .reverseRange(RedisConstant.BLOCK_TR_KEY, start, start + size - 1)  // 使用 reverseRange 获取逆序
                .stream()
                .map(json -> gson.fromJson(json, BlockchainTransaction.class))  // 简化为 Lambda 表达式
                .collect(Collectors.toList());

        return RUtils.success(collect);
    }

    @Operation(summary = "修改土地状态")
    @PostMapping("/status/{status}")
    public Result updateLandStatus(@PathVariable Integer status, Integer id) {
        FarmlandInfo info = facilityInfoService.getById(id);
        facilityInfoService.updateById(info.setIsActive(status));
        return RUtils.success();
    }

    @Operation(summary = "查询用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        User user = userService.getById(loginUser.getUserId());
        UpdateUserVo updateUserVo = BeanUtil.copyProperties(user, UpdateUserVo.class);
        return RUtils.success(updateUserVo);
    }

    @Operation(summary = "修改用户信息")
    @PutMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UpdateUserDto updateUserDto) {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        updateUserDto.setId(Math.toIntExact(loginUser.getUserId()));
        boolean success = userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId, updateUserDto.getId())
                .set(updateUserDto.getUsername() != null, User::getUsername, updateUserDto.getUsername())
                .set(updateUserDto.getUserImage() != null, User::getUserImage, updateUserDto.getUserImage())
        );
        if (!success) {
            return RUtils.Err(0,"更新失败，用户不存在或信息未变更");
        }
        return RUtils.success();
    }

}
